<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="商品名称">
                <a-input placeholder="请输入商品名称" v-model="queryParam.search_words" allowClear> </a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="来源">
                <a-select placeholder="请选择来源" :default-value="0" @change="onSourceChange">
                  <a-select-option v-for="(item, index) of sourceList" :key="index">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="商品分类">
                <div class="select">
                  <a-cascader
                    allowClear
                    :options="catList"
                    @change="onCascaderChange"
                    :fieldNames="{ label: 'title', value: 'id', children: 'children' }"
                    placeholder="请选择商品分类"
                  />
                  <a-button type="primary" @click="clearData">查询</a-button>
                </div>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="最低价">
                <div class="select">
                  <a-input-number
                    :precision="2"
                    style="width: 100%"
                    id="inputNumber"
                    v-model="queryParam.price_left"
                    :min="0"
                  />
                </div>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="最高价">
                <div class="select">
                  <a-input-number
                    :precision="2"
                    style="width: 100%"
                    id="inputNumber"
                    v-model="queryParam.price_right"
                    :min="queryParam.price_left"
                  />
                </div>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>

    <a-card :bordered="false" class="card_style_re" style="margin-top: 20px">
      <!-- <div class="flex">
        <div></div>
        <div>
          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item @click="batch()">批量选品</a-menu-item>
            </a-menu>
            <a-button> 批量操作 </a-button>
          </a-dropdown>
        </div>
      </div> -->

      <div class="goodsList" v-if="goodsList.length > 0">
        <div class="item" v-for="item of goodsList" :key="item.id">
          <div class="box">
            <div class="img">
              <!-- <div class="checked">
                <a-checkbox v-model="item.checked"> </a-checkbox>
              </div> -->

              <img :src="item.cover" alt="" />
              <div class="des">
                <a href="javascript:;" @click="goDetail(item.id)">查看详情</a>
                <a href="javascript:;" @click="checkGoods(item.id)">加入选品</a>
              </div>
            </div>

            <div class="txt">
              <h3>{{ item.title }}</h3>

              <div class="price">
                协议价<span><em>￥</em>{{ formatPrice(item.agreement_price) }}</span>
              </div>
              <div class="price">
                指导价<span><em>￥</em>{{ formatPrice(item.guide_price) }}</span>
              </div>
              <div class="price">
                利润率<span>{{ item.rate }}%</span>
              </div>

              <div class="number">
                销量<em>{{ item.real_sale }}</em>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-else>
        <a-empty />
      </div>
      <div style="text-align: right">
        <a-pagination
          v-model="queryParam.page"
          :pageSize="queryParam.limit"
          :total="totalCount"
          @change="tablePageChange"
        />
      </div>
    </a-card>
    <a-modal v-model="showItemModal" title="商品详情" :footer="null" :destroyOnClose="true" width="700px">
      <el-carousel>
        <el-carousel-item v-for="(item, index) of currentItem.covers" :key="index">
          <el-image :src="item" :preview-src-list="currentItem.covers"></el-image>
        </el-carousel-item>
      </el-carousel>
      <a-descriptions style="margin-top: 20px" :column="1" bordered :title="currentItem.title">
        <a-descriptions-item label="建议分类">
          {{ currentItem.third_category_name }}
        </a-descriptions-item>
        <a-descriptions-item label="单位">
          {{ currentItem.unit }}
        </a-descriptions-item>
        <a-descriptions-item label="协议价">
          <em style="font-size: 12px; font-style: normal">￥</em>{{ formatPrice(currentItem.agreement_price) }}
        </a-descriptions-item>
        <a-descriptions-item label="指导价">
          <em style="font-size: 12px; font-style: normal">￥</em>{{ formatPrice(currentItem.guide_price) }}
        </a-descriptions-item>
        <a-descriptions-item label="营销利润率"> {{ currentItem.activity_rate }}% </a-descriptions-item>
        <a-descriptions-item label="库存">
          {{ currentItem.stock }}
        </a-descriptions-item>
        <a-descriptions-item label="销量">
          {{ currentItem.sale }}
        </a-descriptions-item>
        <a-descriptions-item label="是否包邮">
          {{ currentItem.is_free_shipping == 0 ? '不包邮' : '包邮' }}
        </a-descriptions-item>
        <a-descriptions-item label="规格" v-if="currentItem.specs">
          <a-descriptions :column="1" bordered title="">
            <a-descriptions-item
              :label="item.spec_value_names"
              v-for="(item, index) of currentItem.specs.options"
              :key="index"
            >
              <em style="font-size: 12px; font-style: normal">￥</em>{{ formatPrice(item.agreement_price) }}
            </a-descriptions-item>
          </a-descriptions>
        </a-descriptions-item>
      </a-descriptions>
      <div class="goods-detail" v-html="currentItem.description"></div>
    </a-modal>
    <a-modal
      v-model="showAddModal"
      :closable="false"
      :maskClosable="false"
      title="加入选品"
      :footer="null"
      :destroyOnClose="true"
      width="1200px"
    >
      <a-row :gutter="16" v-if="currentItem.title">
        <a-col :span="12">
          <a-descriptions :column="1" bordered :title="currentItem.title">
            <a-descriptions-item label="建议分类">
              {{ currentItem.third_category_name }}
            </a-descriptions-item>
            <a-descriptions-item label="协议价">
              <em style="font-size: 12px; font-style: normal">￥</em>{{ formatPrice(currentItem.agreement_price) }}
            </a-descriptions-item>
            <a-descriptions-item label="指导价">
              <em style="font-size: 12px; font-style: normal">￥</em>{{ formatPrice(currentItem.guide_price) }}
            </a-descriptions-item>
            <a-descriptions-item label="营销利润率"> {{ currentItem.activity_rate }}% </a-descriptions-item>
            <a-descriptions-item label="规格" v-if="currentItem.specs">
              <a-descriptions :column="1" bordered title="">
                <a-descriptions-item
                  :label="item.spec_value_names"
                  v-for="(item, index) of currentItem.specs.options"
                  :key="index"
                >
                  <em style="font-size: 12px; font-style: normal">￥</em>{{ formatPrice(item.agreement_price) }}
                </a-descriptions-item>
              </a-descriptions>
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
        <a-col :span="12">
          <a-form-model
            ref="ruleForm"
            :rules="formRules"
            :model="addForm"
            :label-col="{ span: 5 }"
            :wrapper-col="{ span: 19 }"
          >
            <a-form-model-item label="商品名称" prop="name">
              <a-input placeholder="请输入商品名称" v-model="addForm.name" />
            </a-form-model-item>
            <a-form-model-item label="商品分类" hasFeedback prop="cat">
              <a-select mode="tags" allow-clear style="width: 100%" placeholder="请选择分类" v-model="addForm.cat">
                <a-select-option v-for="item of goodsCatList" :key="item.id" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item label="铺货价" prop="price">
              <a-input-number
                style="width: 100%"
                placeholder="请输入铺货价"
                v-model="addForm.price"
                :precision="2"
                :min="formatPrice(currentItem.agreement_price)"
              />
            </a-form-model-item>
            <a-form-model-item label="批发价" prop="wholesale_price">
              <a-input-number
                style="width: 100%"
                placeholder="请输入批发价"
                v-model="addForm.wholesale_price"
                :precision="2"
                :min="formatPrice(currentItem.agreement_price)"
              />
            </a-form-model-item>
            <a-form-model-item label="建议零售价" prop="original_price">
              <a-input-number
                style="width: 100%"
                placeholder="请输入建议零售价"
                v-model="addForm.original_price"
                :precision="2"
                :min="formatPrice(currentItem.agreement_price)"
              />
            </a-form-model-item>
            <a-form-model-item label="规格">
              <a-descriptions :column="1" title="" bordered>
                <a-descriptions-item label="规格名称">
                  <a-row :gutter="16">
                    <a-col :span="12"> 铺货价 </a-col>
                    <a-col :span="12"> 批发价 </a-col>
                  </a-row>
                </a-descriptions-item>
                <a-descriptions-item
                  :label="item.spec_value_names"
                  v-for="(item, index) of currentItem.specs.options"
                  :key="index"
                >
                  <a-row :gutter="16" v-if="addForm.attr.length > 0">
                    <a-col :span="12">
                      <a-input-number
                        style="width: 100%"
                        placeholder="请输入铺货价"
                        :precision="2"
                        v-model="addForm.attr[index].price"
                        :min="formatPrice(item.agreement_price)"
                      />
                    </a-col>
                    <a-col :span="12">
                      <a-input-number
                        style="width: 100%"
                        placeholder="请输入批发价"
                        :precision="2"
                        v-model="addForm.attr[index].wholesale_price"
                        :min="formatPrice(item.agreement_price)"
                      />
                    </a-col>
                  </a-row>
                </a-descriptions-item>
              </a-descriptions>
            </a-form-model-item>
            <a-form-model-item :wrapper-col="{ span: 19, offset: 5 }">
              <a-button @click="showAddModal = false"> 取消 </a-button>
              <a-button style="margin-left: 10px" :loading="btnLoading" type="primary" @click="onAdd">
                确认加入
              </a-button>
            </a-form-model-item>
          </a-form-model>
        </a-col>
      </a-row>
    </a-modal>
    <a-modal
      v-model="isUpdateGoods"
      @ok="toBindSku(stbz_id)"
    >产品已经存在，是否更新</a-modal>
  </page-header-wrapper>
</template>

<script>
import tabList from '@/views/saas/components/tabList.vue'
import { getCatList, getGoodsList, getGoodsItem, addCloudGoods, checkGoodsImport } from '@/api/purchase/stbz'
import { getGoodsCatList } from '@/api/purchase/supplier'

export default {
  components: {
    tabList,
  },
  data() {
    return {
      sourceList: [
        {
          id: 0,
          name: '全部',
        },
        {
          id: 1,
          name: '云仓',
        },
        {
          id: 2,
          name: '京东',
        },
        {
          id: 6,
          name: '阿里巴巴',
        },
        {
          id: 7,
          name: '天猫',
        },
        {
          id: 8,
          name: '苏宁',
        },
        {
          id: 11,
          name: '华南一仓',
        },
        {
          id: 14,
          name: '华东一仓',
        },
        {
          id: 15,
          name: '淘宝',
        },
      ],
      btnLoading: false,
      showItemModal: false,
      showAddModal: false,
      catList: [],
      goodsList: [],
      totalCount: 0,
      // 搜索参数
      queryParam: {
        search_words: '',
        category_id: 0,
        page: 1,
        limit: 10,
        source: 0,
        price_left: 0,
        price_right: 0
      },
      currentItem: {},
      goodsCatList: [],
      addForm: {
        name: '',
        cat: [],
        price: 0,
        wholesale_price: 0,
        original_price: 0,
        attr: [],
      },
      formRules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        cat: [{ required: true, message: '请选择商品类别', trigger: 'change' }],
        price: [{ required: true, message: '请输入商品铺货价', trigger: 'blur' }],
        wholesale_price: [{ required: true, message: '请输入商品批发价', trigger: 'blur' }],
        original_price: [{ required: true, message: '请输入商品建议零售价', trigger: 'blur' }],
      },
      isUpdateGoods: false,
      stbz_id: 0
    }
  },
  created() {
    this.getCat()
    this.getGoodsList()
    this.getGoodsCatList()
  },
  watch: {
    showAddModal: function (val) {
      if (!val) {
        this.addForm = {
          name: '',
          cat: [],
          price: 0,
          wholesale_price: 0,
          original_price: 0,
          attr: [],
        }
      }
    },
    'queryParam.source': function (val) {
      this.queryParam.category_id = 0
      this.getCat()
    }
  },
  methods: {
    async checkGoods(id) {
      this.stbz_id = id;
      const res = await checkGoodsImport({id: id})
      if (res.code === 0) {
        if (res.data.data.id) {
          this.isUpdateGoods = true
        } else {
          this.toBindSku(id)
        }
      }
    },
    batch() {},
    onSourceChange(index) {
      this.queryParam.source = this.sourceList[index].id
    },
    async getCat() {
      const res = await getCatList({ source: this.queryParam.source })
      if (res.code == 0) {
        this.catList = res.data
      }
    },
    onCascaderChange(val) {
      this.queryParam.category_id = val[val.length - 1]
    },
    // 分页请求
    tablePageChange(e) {
      this.queryParam.page = e
      this.getGoodsList()
    },
    clearData() {
      this.queryParam.page = 1
      this.getGoodsList()
    },
    async getGoodsList() {
      const hide = this.$message.loading('请求中...')

      const res = await getGoodsList(this.queryParam)
      hide()
      if (res.code == 0) {
        this.totalCount = res.data.count
        this.goodsList = res.data.list
      }
    },
    formatPrice(price) {
      const a = price * 0.01
      return a.toFixed(2) + ''
    },
    goDetail(id) {
      this.getDetail(id, () => {
        this.showItemModal = true
      })
    },
    async getDetail(id, callback) {
      const hide = this.$message.loading('请求中...')
      const res = await getGoodsItem({ id })
      hide()
      if (res.code == 0) {
        this.currentItem = res.data
        callback()
      }
    },
    async getGoodsCatList() {
      const res = await getGoodsCatList({ is_show: 1 })
      if (res.code == 0) {
        this.goodsCatList = res.data
      }
    },
    toBindSku(id) {
      this.getDetail(id, () => {
        this.addForm.name = this.currentItem.title
        this.addForm.price = this.formatPrice(this.currentItem.agreement_price)
        this.addForm.wholesale_price = this.formatPrice(this.currentItem.agreement_price)
        this.addForm.original_price = this.formatPrice(this.currentItem.guide_price)
        this.addForm.attr = this.handleAttr(this.currentItem.specs, this.currentItem.cover)
        this.showAddModal = true
        this.isUpdateGoods = false
      })
    },
    handleAttr(specs, image) {
      const attr = []
      for (let i = 0; i < specs.options.length; i++) {
        const attr_list = []
        const value_ids = specs.options[i].spec_value_ids.split('_')
        for (let ii = 0; ii < value_ids.length; ii++) {
          for (let iii = 0; iii < specs.values.length; iii++) {
            if (value_ids[ii] == specs.values[iii].id) {
              for (let iiii = 0; iiii < specs.names.length; iiii++) {
                if (specs.names[iiii].id == specs.values[iii].spec_name_id) {
                  attr_list.push({
                    attr_group_name: specs.names[iiii].name == '默认' ? '规格' : specs.names[iiii].name,
                    attr_name: specs.values[iii].name,
                  })
                }
              }
            }
          }
        }
        attr.push({
          attr_list: attr_list,
          num: specs.options[i].stock,
          price: this.formatPrice(specs.options[i].agreement_price),
          wholesale_price: this.formatPrice(specs.options[i].agreement_price),
          no: specs.options[i].id,
          pic: specs.options[i].image == '' ? image : specs.options[i].image,
          share_commission_first: '',
          share_commission_second: '',
          share_commission_third: '',
        })
      }

      return attr
    },
    onAdd() {
      this.$refs['ruleForm'].validate(async (valid) => {
        if (valid) {
          this.btnLoading = true
          const res = await addCloudGoods({ ...this.addForm, id: this.currentItem.id })
          this.btnLoading = false
          if (res.code == 0) {
            this.$message.success('添加成功')
            this.showAddModal = false
          }
        } else {
          return false
        }
      })
    },
  },
}
</script>
<style lang="less" scoped>
.searchBox {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  /deep/ .ant-input-affix-wrapper {
    width: 220px;
    margin-right: 20px;
  }
  .select {
    display: flex;
    align-items: center;
    margin-right: 15px;
  }
}
.tip {
  line-height: normal;
  margin-bottom: 0;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
}
.name {
  display: flex;
  align-items: center;
  .pic {
    width: 48px;
    min-width: 48px;
    height: 48px;
    border-radius: 4px;
    overflow: hidden;
    margin-right: 24px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .info {
    flex: auto;
    width: 0;
    display: flex;
    flex-direction: column;
    font-size: 14px;
    span {
      width: 100%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    span:nth-child(2) {
      color: rgba(0, 0, 0, 0.45);
      margin-top: 6px;
    }
  }
}
.goods-info {
  display: flex;
  align-items: flex-start;
  .goods-pic {
    width: 48px;
    height: 48px;
    border-radius: 4px;
  }
  .info-box {
    margin-left: 24px;
    .goods-name {
      display: block;
      width: 160px;
      font-size: 14px;
      color: rgba(0, 0, 0, 0.65);
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
  }
}

.goodsList {
  display: flex;
  flex-wrap: wrap;
  margin-left: -24px;

  .item {
    width: 20%;
    display: inline-block;
  }

  .box {
    margin: 0 0 24px 24px;
    border: 1px solid #f0f2f5;
    border-radius: 4px;

    &:hover {
      .img .des {
        opacity: 1;
      }
    }
  }

  .txt {
    padding: 16px;
    color: rgba(0, 0, 0, 0.45);

    h3 {
      font-size: 14px;
      line-height: 24px;
      height: 48px;
      display: -webkit-box;
      white-space: normal;
      text-overflow: ellipsis;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      word-break: break-all;
      overflow: hidden;
      color: #000;
    }

    .price {
      padding-bottom: 5px;
      font-size: 14px;

      em {
        font-size: 12px;
        font-style: normal;
      }

      span {
        margin-left: 5px;
        font-size: 16px;
        color: #ff4d4f;
      }
    }

    .name,
    .number,
    .price {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .number {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;

      em {
        margin-left: 5px;
        font-style: normal;
        color: #1890ff;
      }
    }
  }

  .img {
    position: relative;
    padding-top: 100%;

    img {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .des {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      display: flex;
      background: #0084fe;
      transition: 0.3s;
      opacity: 0;

      &:after {
        content: '';
        position: absolute;
        left: 50%;
        top: 50%;
        margin: -6px 0 0 -0.5px;
        width: 1px;
        height: 12px;
        background: #fff;
      }

      a {
        overflow: hidden;
        text-align: center;
        width: 50%;
        height: 28px;
        line-height: 28px;
        color: #fff;
      }
    }
  }
}
.goods-detail {
  margin-top: 20px;
}
.goods-detail /deep/ img {
  width: 100%;
  height: auto;
}

.checked {
  position: absolute;
  right: 18px;
  top: 18px;
  z-index: 3;
}

.flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
